package org.sxp.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Spring Context 工具类
 *
 *
 */
@Slf4j
@Component
public class SpringContextUtils implements ApplicationContextAware {
	public static ApplicationContext applicationContext; 

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		SpringContextUtils.applicationContext = applicationContext;
	}

	public static <T> T getBean(String name) {
		T bean = null;
		try{
			bean = hasLoadContext() ? (T)applicationContext.getBean(name) : null;
		}catch (NoSuchBeanDefinitionException ex){
			log.error(ex.getMessage(), ex);
		}
		return  bean;
	}
	public static <T> T getBean(Class<T> requiredType) {
		return applicationContext.getBean(requiredType);
	}

	public static <T> T getBean(String name, Class<T> requiredType) {
		return applicationContext.getBean(name, requiredType);
	}

	public static <T> T registerByProperties(String name, Class<T> clazz, Map<String, Object> params) {
		BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
		if (params != null && params.size() > 0) {
			params.forEach((s, o) -> {
				beanDefinitionBuilder.addPropertyValue(s, o);
			});
		}

		BeanDefinition beanDefinition = beanDefinitionBuilder.getRawBeanDefinition();
		BeanDefinitionRegistry beanFactory = (BeanDefinitionRegistry)getApplicationContext();
		beanFactory.registerBeanDefinition(name, beanDefinition);
		return applicationContext.getBean(name, clazz);
	}
	public static ApplicationContext getApplicationContext() {
		return hasLoadContext() ? applicationContext : null;
	}

	private static boolean hasLoadContext() {
		if (applicationContext == null) {
			throw new IllegalStateException("SpringContextUtil初始化失败,请在applicationContext.xml中定义SpringContextUtil");
		} else {
			return true;
		}
	}

	public static <T> Map<String, T> getBeansOfType(Class<T> type){
		return applicationContext.getBeansOfType(type);
	}

	public static boolean containsBean(String name) {
		return applicationContext.containsBean(name);
	}

	public static boolean isSingleton(String name) {
		return applicationContext.isSingleton(name);
	}

	public static Class<? extends Object> getType(String name) {
		return applicationContext.getType(name);
	}

}